package com.eagle.coders.common.ui.lookup;

import java.util.Collection;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.openide.util.Lookup;

import com.eagle.coders.common.ui.interfaces.IComponent;
import com.eagle.coders.common.ui.interfaces.ITaskBar;
import com.eagle.coders.common.ui.interfaces.IToolbar;

/**
 * 
 * @author Anees
 *
 */
public class EagleLookup {
	
	private static final String USECASES_CONFIG = "META-INF/usecase/";
	private static final String BASE_USECASES_CONFIG= "usecases.xml";
	private static final String DOMAIN_CONFIG = "META-INF/domain/";
	
	
	/**
	 * 
	 * @param domainXML
	 * @return
	 */
	public static String getDomainXmlConfig(String domainXML){
		
		String xml =  EagleLookup.class.getClassLoader().getResource(DOMAIN_CONFIG+domainXML).getFile();
		try{
			
			SAXReader saxReader = new SAXReader();
			Document doc = saxReader.read(xml);
			return doc.getRootElement().asXML();
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 
	 * @return
	 */
	public static IComponent getUsecaseFromXml(){
		return getUsecaseFromXml(null, null);
	}
	/**
	 * 
	 * @return
	 */
	public static IComponent getUsecaseFromXml(String usecaseId){
		
		return getUsecaseFromXml(null, usecaseId);
	}
	
	/**
	 * 
	 * @param usecases
	 * @return
	 */
	public static IComponent getUsecaseFromXml(String usecases, String usecaseId){
		
		IComponent.BaseComponent component = new IComponent.BaseComponent();
		
		String xml = "";
		try{
			if(null == usecases)
				xml = EagleLookup.class.getClassLoader().getResource(USECASES_CONFIG+BASE_USECASES_CONFIG).getFile();
			else
				xml = EagleLookup.class.getClassLoader().getResource(USECASES_CONFIG+usecases).getFile();
			
			SAXReader saxReader = new SAXReader();
			Document doc = saxReader.read(xml);
			if(null != usecaseId){
				Node node = doc.selectSingleNode("usecases/usecase[@id='"+usecaseId+"']");
				component.setIdentity(usecaseId);
				component.setXml(node.asXML());
			}else{
				
				Element element = doc.getRootElement();
				component.setXml(element.asXML());
			}
			
			return component;
			
		}catch(Exception e){
			e.printStackTrace();
			return null;
//			throw new Exception(e.getMessage());
		}
		
	}
	
	/**
	 * 
	 * @return
	 */
	public static Collection<? extends IComponent> getUsecaseLookup(){
		
		return Lookup.getDefault().lookupAll(IComponent.class);
	}
	
	/**
	 * 
	 * @return
	 */
	public static Collection<? extends IToolbar> getToolBar(){
		
		return Lookup.getDefault().lookupAll(IToolbar.class);
	}
	
	/**
	 * 
	 * @return
	 */
	public static Collection<? extends ITaskBar> getTaskBar(){
		
		return Lookup.getDefault().lookupAll(ITaskBar.class);
	}

}
